<?php
error_reporting(E_ALL ^ E_NOTICE); // Report all errors except E_NOTICE warnings
//error_reporting(E_ALL); // Report all errors and warnings (very strict, use for testing only)
ini_set('display_errors', 1); // turn error reporting on
//ini_set('log_errors', 1); // log errors
//ini_set('error_log', dirname(__FILE__) . '/error_log.txt'); // where to log errors
/*
IP To Country PHP Script by Mike Challis
Free PHP Scripts - www.642weather.com/weather/scripts.php
Download         - www.642weather.com/weather/scripts/ip-to-country.zip
Live Demo        - www.642weather.com/weather/ip-to-country.php
Contact Mike     - www.642weather.com/weather/contact_us.php

Version: 1.50 - 06-Dec-2008 see changelog.txt for changes

You are free to use and modify the code

This php code provided "as is", and Long Beach Weather (Michael Challis)
disclaims any and all warranties, whether express or implied, including
(without limitation) any implied warranties of merchantability or
fitness for a particular purpose.

Copyright (C) 2008 Mike Challis  (www.642weather.com/weather/contact_us.php)

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*/
$version = 'Version: 1.50 - 06-Dec-2008 - ip-to-country PHP Script by Mike Challis';

// include settings file
require 'ip-to-country-config.php';

// initialize some vars
$ip_input = 0;
$ip_data = array();
$ip_data['error'] = 'none';

// program logic (make decisions)
if (isset($_REQUEST['action']) && ($_REQUEST['action'] == 'check')) {

  if ( isset($_REQUEST['ip']) && !empty($_REQUEST['ip']) ) {
          // use form or query string input IP address
          $user_ip = ctf_clean_input($_REQUEST['ip']);
          $ip_input = 1;
  } else {
          // use user's detected IP address
          $user_ip = ctf_clean_input($_SERVER['REMOTE_ADDR']);
  }


  // check the input, then process now.

 // what format to output, text, xml, or html?
 if (isset($_REQUEST['output']) && ($_REQUEST['output'] == 'text') && $C['include'] == 0) {
         $ip_data['output'] = 'text';
         validate_input($user_ip);
         find_country($user_ip);
         output_text();

 } else if (isset($_REQUEST['output']) && ($_REQUEST['output'] == 'xml') && $C['include'] == 0) {
         $ip_data['output'] = 'xml';
         validate_input($user_ip);
         find_country($user_ip);
         output_xml();

 } else {
         $ip_data['output'] = 'html';
         validate_input($user_ip);
         find_country($user_ip);
         output_html();
 }

} else {
       // just print input forms
       do_welcome();

}

//exit;

function do_welcome()  {
  global $C, $version;

if ($C['include'] == 0)  echo $C['header'];

echo '

<p>
Find the country and host info for an IP address:
</p>


<form method="post" name= "ip_check" action="'.$C['file_name'].'">
<input type="hidden" name="action" value="check" />
<label for="ip">IP Address:</label> <input type="text" id="ip" name="ip" />
<input type="submit" value="Check IP" name="submit" /> <br />
example: 70.56.98.195 (Leave blank to check your own IP)
</form>

';

echo "<!-- $version -->\n";
if ($C['include'])  echo "<!-- include mode on -->\n";
echo "<!-- http://www.642weather.com/weather/scripts.php -->\n\n";

echo $C['credit'];

if ($C['include'] == 0)  echo $C['footer'];

}

function find_country($user_ip) {
   global $C, $ip_data, $ip_input;

  if(!empty($user_ip) && $ip_data['error'] == 'none') {

    $dbh = mysql_connect($C['dbhost'],$C['dbuser'],$C['dbpass']);
    if (!$dbh) die('Could not connect: ' . mysql_error());
    mysql_select_db($C['dbname']) or die(mysql_error());

    $query  = "SELECT country_name, country_code2
    FROM country_info WHERE inet_aton('$user_ip') >= ip_from
    AND inet_aton('$user_ip') <= ip_to";

    $result = mysql_query($query) or die("Invalid query: " . mysql_error().__LINE__.__FILE__);
    $ip_data  = mysql_fetch_array($result);

    mysql_close($dbh);

    if(empty($ip_data['country_name']))  $ip_data['country_name']  = 'n/a';
    if(empty($ip_data['country_code2'])) $ip_data['country_code2'] = 'n/a';

    $ip_data['ip_host'] = '';
    $ip_data['ip_host'] = gethostbyaddr($user_ip);

    if ($ip_data['ip_host'] == $user_ip) {
       $ip_data['ip_host'] = 'n/a';
    }

    $ip_data['ip'] = $user_ip;
    $ip_data['error'] = 'none';

 } else {

    $ip_data['country_name']  = 'n/a';
    $ip_data['country_code2'] = 'n/a';
    $ip_data['ip_host']       = 'n/a';
    $ip_data['ip']            = 'n/a';
 }


}

function output_html() {
   global $C, $ip_data, $ip_input;

  if ($C['include'] == 0)  echo $C['header'];

   if ($ip_data['ip_host'] == 'n/a') {
     $ip_data['ip_host'] = 'No host name found for this IP address';
   }


  echo '
 <table>
  <tr><td colspan="2"><strong>Results of your IP check:</strong></td></tr>
  <tr><td>IP:</td><td>'.$ip_data['ip'].'</td></tr>
  <tr><td>Host:</td><td>'.$ip_data['ip_host'].'</td></tr>
  <tr><td>Country:</td><td>'.$ip_data['country_name'].'</td></tr>
  <tr><td valign="top">Country Code:</td><td>'.$ip_data['country_code2'];

 if($ip_data['error'] == 'none') {
  $ip_data['country_code2'] = strtolower($ip_data['country_code2']);
  if (is_file( $C['path_to_imgs'] . '/' . $ip_data['country_code2']  . $C['country_img_type'] )) {
     echo '<br />
     <img src="'. $C['url_to_imgs'] . '/' . $ip_data['country_code2']  . $C['country_img_type'].'" alt="'.$ip_data['country_code2'].'" />';
  } else {
     echo '<br />Error: <a href="'. $C['url_to_imgs'] . '/' . $ip_data['country_code2']  . $C['country_img_type'].'">Country flag image</a> not found, be sure the country-flags images directory is installed and that you have set the path and url correctly in settings';
  }
 }
  echo '</td></tr>';

  if ($ip_input == 0){
    echo '
    <tr><td>Browser:</td><td>'.ctf_clean_input($_SERVER['HTTP_USER_AGENT']) .'</td></tr>';
  }

  echo '
</table>

<p>
<strong><a href="'.$C['file_name'].'">Try another IP lookup</a></strong>
</p>

<p>
<strong>More searches for IP '.$ip_data['ip'].':</strong>
</p>

<p>
Spammer and Blacklists:
</p>

<ul>
<li><a href="http://www.stopforumspam.com/search?q='.$ip_data['ip'].'" target="_blank">Search - Stop Forum Spam</a></li>
<li><a href="http://openrbl.org/client/#'.$ip_data['ip'].'" target="_blank">Search - Openrbl DNSBL RBL Blacklist</a></li>
</ul>

<p>
Regional whois-servers:
</p>

<ul>
<li><a href="http://www.afrinic.net/cgi-bin/whois?searchtext='.$ip_data['ip'].'" target="_blank">AfriNIC (Africa)</a></li>
<li><a href="http://www.apnic.net/apnic-bin/whois2.pl?searchtext='.$ip_data['ip'].'" target="_blank">APNIC (Asia Pacific region)</a></li>
<li><a href="http://ws.arin.net/cgi-bin/whois.pl?queryinput='.$ip_data['ip'].'" target="_blank">ARIN (North America, a portion of the Caribbean and sub-Saharan Africa)</a></li>
<li><a href="http://lacnic.net/cgi-bin/lacnic/whois?query='.$ip_data['ip'].'" target="_blank">LACNIC (Latin American and Caribbean region)</a></li>
<li><a href="http://www.ripe.net/perl/whois?searchtext='.$ip_data['ip'].'" target="_blank">RIPE (Europe, the Middle East and parts of Africa and Asia)</a></li>
</ul>

';

// text output and xml output can be used for advanced uses of the country to ip data by remote lookup
// e-commerce is an example of a use for country to IP (see readme.txt for more info of advanced uses)
// (text output and xml output) options can be disabled
if ($C['include']) $C['enable_xml'] = 0;
if ($C['enable_xml'])  {

echo '
<p>
Other output options:
</p>

<ul>
<li><a href="'.$C['file_name'].'?action=check&amp;ip='.$ip_data['ip'].'&amp;output=text">text</a></li>
<li><a href="'.$C['file_name'].'?action=check&amp;ip='.$ip_data['ip'].'&amp;output=xml">xml</a></li>
</ul>

';
}

echo $C['credit'];

if ($C['include'] == 0)  echo $C['footer'];

}

function output_text() {
   global $C, $ip_data;

   echo 'IP='.$ip_data['ip'].', IP_HOST='.$ip_data['ip_host'].', COUNTRY_NAME='.$ip_data['country_name'].', COUNTRY_CODE2='.$ip_data['country_code2'].', ERROR='.$ip_data['error'];

}

function output_xml() {
   global $C, $ip_data, $ip_input;

   header('Content-type: text/xml');

   echo '<?xml version="1.0" encoding="UTF-8"?>
<response>
<ip_data IP="'.$ip_data['ip'].'" IP_HOST="'.$ip_data['ip_host'].'" COUNTRY_NAME="'.$ip_data['country_name'].'" COUNTRY_CODE2="'.$ip_data['country_code2'].'" ERROR="'.$ip_data['error'].'" />
</response>
';
}

function input_error($reason) {
      global $C, $ip_data;

    // handle error differently for different output types
    if ($ip_data['output'] != 'html') {
       $ip_data['error'] = $reason;
       return;
    }

    echo '
    <p>
    <b>Error: '.$reason.'</b>
    </p>

    <p>
    <a href="JavaScript:history.back()">Go back</a><br>
    </p>

    ';
  exit;
}


function validate_input($user_ip) {

   if (!preg_match("/^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$/i", $user_ip)) {
      input_error('Invalid IP address');
      return false;
   }

   // use this method of address-to-number conversion to validate IP addresses using the PHP function ip2long().
   if (($binIp = ip2long($user_ip)) === false) {
         input_error('Invalid IP address');
         return false;
    } else {
        return true;
   }
}

// functions for protecting and validating form input vars
function ctf_clean_input($string) {
    if (is_string($string)) {
      return trim(ctf_sanitize_string(strip_tags(ctf_stripslashes($string))));
    } elseif (is_array($string)) {
      reset($string);
      while (list($key, $value) = each($string)) {
        $string[$key] = ctf_clean_input($value);
      }
      return $string;
    } else {
      return $string;
    }
}

function ctf_sanitize_string($string) {
    $string = ereg_replace(' +', ' ', trim($string));
    return preg_replace("/[<>]/", '_', $string);
}

function ctf_stripslashes($string) {
        if (get_magic_quotes_gpc()) {
                return stripslashes($string);
        } else {
                return $string;
        }
}

function ctf_output_string($string) {
    return str_replace('"', '&quot;', $string);
}


?>